let {Router} = require('express');
let {resolve} = require('path');
//引入userModel模块
let userModel=require('../model/userModel');
//引入邮件模块
let sendMail=require('../mail/sendMail');

let router = new Router();

router.post('/login',async (req,res)=>{
    let {user,pwd}=req.body;
    try{
        let findUserResult=await userModel.findOne({user,pwd});
        let findEmailResult=await userModel.findOne({email:user,pwd});
        if(!findUserResult && !findEmailResult){
            res.send("0");
        }else{
            let Result=findUserResult?findUserResult:findEmailResult;
            req.session._id=Result._id;
            res.send("1");
        }
    }catch(err){
        console.log(err);
        res.send("-1")
    }
});

router.post('/register',async (req,res)=>{
    let {user,pwd,email}=req.body;
    try{
        await userModel.create({user,pwd,email});
        res.send("1")

    }catch(err){
        console.log(err);
        res.send("0")
    }

});

router.post('/findpass',async (req,res)=>{
    let {email,pwd}=req.body;
    try{
        await userModel.updateOne({email},{$set:{pwd}});
        res.send("1")

    }catch(err){
        console.log(err);
        res.send("0")
    }
});

router.post('/check',async (req,res)=>{
    let {check} = req.body;
    if(check.type==='email'){
        let findOneResult=null;
        if(!check.sendOnly){
            findOneResult=await userModel.findOne({email:check.data});
        }
        if(findOneResult){
            res.send({result:0})
        }else{
            let code=create4rand();
            console.log(code);
            sendMail(check.data,code);
            res.send({result:code})
        }
    }else if(check.type==='user'){
        let findOneResult=await userModel.findOne({user:check.data});
        if(findOneResult){
            res.send({result:0})
        }else{
            res.send({result:1})
        }
    }

});
function create4rand(){
    let a=parseInt(Math.random()*10);
    let b=parseInt(Math.random()*10);
    let c=parseInt(Math.random()*10);
    let d=parseInt(Math.random()*10);
    let code=`${a}${b}${c}${d}`;
    return code
}
module.exports = router;